package com.wl.bbs.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.wl.bbs.dao.TopicMapper;
import com.wl.bbs.entity.Result;
import com.wl.bbs.entity.Topic;
import com.wl.bbs.entity.User;
import com.wl.bbs.service.BizException;
import net.sf.jsqlparser.statement.select.Top;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/topic")
public class TopicController {

    @Autowired
    private TopicMapper topicMapper;

    @RequestMapping("/latest")
    public List<Topic> queryLatestTopics() {
        return topicMapper.selectLatestTopics();
    }

    @RequestMapping("queryByBid")
    public Page<Topic> queryByBid(int bid, int page, int rows){
        Page<Topic> p = new PageDto<>(page, rows);
//        LambdaQueryWrapper<Topic> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Topic::getBoardid, bid);
//        return topicMapper.selectPage(p, lqw);
        return topicMapper.selectByBid(bid, p);
    }

    @RequestMapping("queryById")
    public Topic queryById(int id){
        return topicMapper.queryById(id);
    }

    // @RequestBody ==> axios.post("...", 非 URLSearchParams 对象)
    @PostMapping("post")
    public Result post(@RequestBody @Valid Topic topic, Errors errors, @SessionAttribute User myinfo) throws BizException {
        if(errors.hasErrors()){
            // TODO 页面代码待实现
            throw new BizException("验证错误!", errors.getAllErrors());
        }
        topic.setUid(myinfo.getId());
        topicMapper.insert(topic);
        return new Result(1,"发帖成功!", null);
    }

    @RequestMapping("searchByField")
    public Page<Topic> searchByField(int bid, String cname, String title, int page, int rows){
        Page<Topic> p = new PageDto<>(page, rows);
        return topicMapper.searchByField(bid, cname, title, p);
    }
}
